<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="id ? '编辑月卡':'添加月卡'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <!-- 车辆信息 -->
        <div class="form">
          <el-form ref="cardFrom" :model="cardFrom" label-width="100px" :rules="CardRules">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="cardFrom.personName" placeholder="请输入车主姓名" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="cardFrom.phoneNumber" placeholder="请输入联系方式" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="cardFrom.carNumber" placeholder="请输入车辆号码" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="cardFrom.carBrand" placeholder="请输入车辆品牌" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <!-- 月卡缴费信息 -->
        <div class="form">
          <el-form ref="feeFrom" label-width="100px" :model="feeCardFrom" :rules="FeeCardRules">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeCardFrom.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeCardFrom.paymentAmount" placeholder="请输入支付金额" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeCardFrom.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetFrom">重置</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addMonthCardAPI, getCardDetailAPI, editMonthCardAPI } from '@/api/card'
export default {
  name: 'AddMonthCard',
  data() {
    // 车牌自定义校验方法：
    // value 输入框内容
    // callback函数 如果验证失败 return callback(new Error('失败的原因'))
    // callback函数 如果验证成功 return callback()
    const checkCarNumber = function(rule, value, callback) {
      const reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的车牌号码'))
      }
    }

    return {
      // 月卡表单信息
      cardFrom: {
        personName: '', // 车主姓名
        phoneNumber: '', // 联系方式
        carNumber: '', // 车牌号码
        carBrand: ''// 车辆品牌
      },
      // 月卡缴费表单信息
      feeCardFrom: {
        payTime: '', // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: '' // 支付方式
      },
      // 月卡校验规则
      CardRules: {
        personName: [
          {
            required: true, message: '请输入车主姓名', trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true, message: '请输入联系方式', trigger: 'blur'
          },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入正确的手机号码', trigger: 'blur'
          }
        ],
        carNumber: [
          {
            required: true, message: '请输入车辆号码', trigger: 'blur'
          },
          // 验证车牌号码
          { validator: checkCarNumber, trigger: 'blur' }
        ],
        carBrand: [
          {
            required: true, message: '请输入车辆品牌', trigger: 'blur'
          }
        ]
      },
      // 缴费校验规则
      FeeCardRules: {
        payTime: [
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ]
      },
      // 支付方式列表
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '线下'
        }
      ],
      pickerOptions: {
        // 禁止选择今天之前的日期
        disabledDate(time) {
          // 86400 * 1000是一天的毫秒数
          return time.getTime() < Date.now() - 86400 * 1000
        }
      }
    }
  },
  computed: {
    id() {
      // 查询参数获取id
      return this.$route.query.id
    }
  },
  created() {
    if (this.id) {
      this.getCardDetail()
    }
  },
  methods: {
    onSubmit() {
      // 对两个表单进行兜底校验
      // Promise.all(数组)  数组里面放的是promise对象
      const promises = [this.$refs.cardFrom.validate(), this.$refs.feeFrom.validate()]

      Promise.all(promises).then(async() => {
        try {
          const obj = {
            ...this.cardFrom,
            ...this.feeCardFrom,
            cardStartDate: this.feeCardFrom.payTime[0],
            cardEndDate: this.feeCardFrom.payTime[1]
          }
          delete obj.payTime
          //   console.log(obj)
          // 调用addMonthCardAPI发送请求

          // 退回到首页
          this.$router.back()
          if (this.id) {
            await editMonthCardAPI(obj)
            // 编辑成功提示用户
            this.$message.success('编辑月卡成功')
          } else {
            await addMonthCardAPI(obj)
            // 添加成功提示用户
            this.$message.success('添加月卡成功')
          }
        } catch (error) {
        //   console.log(error)
          if (error.response) {
            this.$message.error(error.response.data.msg)
          }
        }
      }).catch(() => {
        console.log('有表单验证不通过')
      })
    },
    resetFrom() {
      this.$refs.cardFrom.resetFields()
      this.$refs.feeFrom.resetFields()
    },
    // 获取月卡详情
    async getCardDetail() {
      try {
        const res = await getCardDetailAPI(this.id)
        console.log(res)
        // 对象结构赋值
        const { personName, phoneNumber, carNumber,
          carBrand, carInfoId } = res.data
        // 将结构的值赋给this.cardFrom
        this.cardFrom = {
          personName,
          phoneNumber,
          carNumber,
          carBrand,
          carInfoId
        }
        // 对象结构赋值
        const { cardStartDate, cardEndDate, paymentAmount, paymentMethod, rechargeId } = res.data
        //   将结构的值赋给this.feeCardFrom
        this.feeCardFrom = {
          payTime: [cardStartDate, cardEndDate],
          paymentAmount,
          paymentMethod,
          rechargeId
        }
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    }
  }
}
</script>

  <style scoped lang="scss">
  .add-card {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      align-items: center;
      padding: 0 20px;
      height: 64px;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;

        .title {
          height: 60px;
          line-height: 60px;
          padding-left: 20px;
        }

        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;

          .el-form {
            display: flex;
            flex-wrap: wrap;

            .el-form-item {
              width: 50%;
            }
          }
        }
      }
      .preview{
        img{
          width: 100px;
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>
